import axios from "axios";
import { debounce, unitNumberWithZero } from "./index";
import { Message } from "element-ui";
import i18n from "@/lang";
import router from "@/router";
import { AuthModule } from "@/store/modules/auth";
import { AppModule } from "@/store/modules/app";
import { __ as _, __ } from '@/lang/old';
import { ResponseCode } from "./responseCode";
import * as tunnyApi from '@/api/tunnyApi';
import Vue from "vue";
import Cookies from 'js-cookie'

export interface PageResponent<T> {
  total: number;
  rows: T[];
}

const responseStatus401 = debounce((res: any) => {
  // if (res.config.url !== "/logout" && res.config.url !== "/token/get") { // 登出接口发生鉴权失败是不做处理
  //   AuthModule.LogOut(false);
  // }
  if (res.data.chances && res.data.chances[0] !== "None") {
    Message({
      message: i18n.t("message.loginFailedWait") + res.data.chances[0],
      type: 'warning'
    });
  } else if (res.data.chances) {
    Message({
      message: i18n.t("message.loginFailed").toString(),
      type: 'warning'
    });
  }
  if(AuthModule.authrole == "system_admin") {
    AuthModule.LogOut(true);
  } else if (AuthModule.authrole === "tenant_admin") {
    AuthModule.LogOut(false);
  }
});
const responseStatus504 = debounce(() => {
  Message({
    message: i18n.t("message.requestTimeout").toString(),
    type: "warning"
  });
});
const responseStatus500 = debounce(() => {
  Message({
    message: i18n.t("message.requestError").toString(),
    type: "warning"
  });
});
const responseStatus429 = debounce((res: any) => {
  if (res.data.reason.indexOf("auth_time_window") !== -1) {
    const startHour = res.data.auth_time_window ? unitNumberWithZero(2, parseInt(JSON.parse(res.data.auth_time_window).start / 60 as any)) : "00";
    const startMinute = res.data.auth_time_window ? unitNumberWithZero(2, parseInt(JSON.parse(res.data.auth_time_window).start % 60 as any)) : "00";
    const endHour = res.data.auth_time_window ? unitNumberWithZero(2, parseInt(JSON.parse(res.data.auth_time_window).end / 60 as any)) : "00";
    const endMinute = res.data.auth_time_window ? unitNumberWithZero(2, parseInt(JSON.parse(res.data.auth_time_window).end % 60 as any)) : "00";
    Message({
      message: i18n.t('message.authTimeWindowMessage', {
        timeSection: startHour + ":" + startMinute + "-" + endHour + ":" + endMinute
      }).toString(),
      type: 'warning'
    });
    router.push("/login");
  } else if (res.data.reason.indexOf("auth_failed") !== -1) {
    Message({
      message: _("Failed to authenticate, please wait #seconds# seconds.", { seconds: res.data.wait }),
      type: "warning"
    });
    router.push("/login");
  } else if (res.data.ldap_user_sync) {
    // Message({
    //   message: `${i18n.t("")}`,
    //   type: "warning"
    // });
  }
});

export function createService(baseURL = "/") {
  const service = axios.create({
    baseURL: baseURL, // url = base url + request url
    timeout: 200000
    // withCredentials: true // send cookies when cross-domain requests
  });

  // Request interceptors
  service.interceptors.request.use(
    (config) => {
      // Add X-Access-Token header to every request, you can add other custom headers here
      if (AuthModule.token) {
        config.headers["X-Access-Token"] = AuthModule.token;
        config.headers.Authorization = "Bearer " + AuthModule.token;
        config.headers["Content-Type"] = "application/json;charset=UTF-8";
        config.headers["Accept-Language"] = AppModule.language === "zh" ? "zh-Hans" : "en-US"; // 让每个请求携带中英文标志
        // Cookies.remove("CMECLOUDTOKEN");
        // Cookies.remove("sensorsdata2015jssdkcross");
        // Cookies.remove("sajssdk_2015_cross_new_user");
        // Cookies.remove("JSESSIONID");
      }
      if (AuthModule.is_cloud_manage_tenant_system) {
        config.baseURL = '/api/web/clouddesktop-management' + baseURL;
        config.headers['cloud-tenant-id'] = AuthModule.cloud_manage_tenant_id;
        config.headers['username'] = AuthModule.cloud_manage_username;
      }
      // if (!AuthModule.token && AuthModule.is_cloud_manage_tenant_system == false) {
      //   Cookies.set("CMECLOUDTOKEN", "d851ba837e524dc18f20c81047de4af3");
      //   Cookies.set("sensorsdata2015jssdkcross", "%7B%22distinct_id%22%3A%2217b2dfa245a5d-0618dcd02bd355-4343363-2073600-17b2dfa245b8cc%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%7D%2C%22%24device_id%22%3A%2217b2dfa245a5d-0618dcd02bd355-4343363-2073600-17b2dfa245b8cc%22%7D");
      //   Cookies.set("sajssdk_2015_cross_new_user", "1");
      //   Cookies.set("JSESSIONID", "E3161EAAFA73E8932D31923FE957DE11");
      // }
      return config;
    },
    (error) => {
      Promise.reject(error);
    }
  );

  // Response interceptors
  service.interceptors.response.use(
    (response) => {
      const res = response.data;
      if (!/[2][0-9]*/.test(response.status.toString())) {
        Message({
          message: res.message || "Error",
          type: "error",
          duration: 5 * 1000
        });
        if (response.status === 401) {
          AuthModule.ResetToken();
          location.reload(); // To prevent bugs from vue-router
        }
        return Promise.reject(new Error(res.message || "Error"));
      } else {
        // console.log(response.data);
        return new ResponseCode(response.data).result;
      }
    },
    (error) => {
      if (error.response) {
        switch (error.response.status) {
          case 401:
            responseStatus401(error.response);
            break;
          case 504:
            responseStatus504();
            break;
          case 500:
            responseStatus500();
            break;
          case 429:
            responseStatus429(error.response);
            break;
        }
      }
      return Promise.reject(error);
    }
  );

  return service;
}

export const cloudTunnyRequest = createService(process.env.VUE_APP_CLOUD_TUNNY_BASE_API)
export const tunnyRequest = createService(process.env.VUE_APP_TUNNY_BASE_API);
export const systemTunnyRequest = createService(process.env.VUE_APP_SYSTEM_TUNNY_BASE_API);
export const pandaRequest = createService(process.env.VUE_APP_PANDA_BASE_API);
export const eagleRequest = createService(process.env.VUE_APP_EAGLE_BASE_API);
export const orinusRequest = createService(process.env.VUE_APP_ORINUS_BASE_API);
export const orsRequest = createService(process.env.VUE_APP_ORS_BASE_API);
export const gentianRequest = createService(process.env.VUE_APP_GENTIAN_BASE_API);
